package com.superm.controller;

import com.superm.entity.Emp;
import com.superm.entity.Role;
import com.superm.mappers.EmpDutiesMapper;
import com.superm.service.EmpDutiesService;
import com.superm.service.RoleService;
import com.superm.utils.EmpContent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(path = "/role")
public class RoleController {
    @Autowired
    private RoleService roleService;
    @Autowired
    private EmpDutiesService empDutiesService;
    @RequestMapping("/index")
    public String index(){
        return "role/allRole";
    }
    @RequestMapping("/All")
    @ResponseBody//异步查出来所有角色
    public Map<String,Object> query(){
        Map<String,Object> map = new HashMap<>();
        List<Role> list = roleService.AllRole();
        map.put("code",0);
        map.put("data",list);
        return map;
    }
    @RequestMapping("/selRole")
    public String selRole(Integer id, Model model){
        Role r = roleService.queryId(id);
        model.addAttribute("Role",r);
        return "role/upRole";
    }
    @RequestMapping("/upRole")
    @ResponseBody
    public Map<String,Object> upRole(Role role){
        Map<String,Object> map = new HashMap<>();
        if (roleService.upRole(role)>0){
            map.put("success",true);
            map.put("msg","修改成功!");
        }else {
            map.put("success",false);
            map.put("msg","修改失败!");
        }
        return map;
    }
    @GetMapping (path ="/addRole")
    public String addRole(){
        return "role/addRole";
    }
    @PostMapping (path ="/addRole")
    @ResponseBody
    public Map<String,Object> addRole(Role role){
        Map<String,Object> map = new HashMap<>();
        Emp emp = EmpContent.EmpUtils();
        role.setrCreator(emp.geteName());
        if (roleService.addRole(role)>0){
            map.put("success",true);
            map.put("msg","添加成功!");
        }else {
            map.put("success",false);
            map.put("msg","添加失败!");
        }
        return map;
    }
    @RequestMapping(path = "/delRole")
    @ResponseBody
    public Map<String,Object> delRole(@RequestParam("rids") String rids){
        List<String> idList = Arrays.asList(rids.split(","));
        Map<String,Object> map = new HashMap<>();

        if(roleService.delRole(rids)>0){
            map.put("success",true);
            map.put("msg","删除成功!");
        }else{
            if(idList.size()>1){
                map.put("success",false);
                map.put("msg","批量删除的角色中某角色被引用");
            }else{
                map.put("success",false);
                map.put("msg","该角色正在被员工引用!");
            }
        }
        return map;
    }
}
